package com.kob.backend.websocket;

import com.alibaba.fastjson2.JSONObject;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.mapper.RecordMapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import com.kob.backend.utils.JwtAuthenticationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/websocket/{token}")  // 注意不要以'/'结尾
public class WebSocketServer {

//    ConcurrentHashMap线程安全，用于维护每个客户端的WebSocketServer对象
//    将userId映射到对应的WebSocketServer
    public static final ConcurrentHashMap<Integer,WebSocketServer> users = new ConcurrentHashMap<>();
    private User user;
//    每个链接是用session来维护，用户信息存到每个session里面
    private Session session = null;

//    WebSocket是多对象，每建立一个连接都会创建一个实例，不是单例,所以不能用常规的自动注入
    public static UserMapper userMapper;
    public static RecordMapper recordMapper;
    private static BotMapper botMapper;
    public static RestTemplate restTemplate;

    public Game game = null;
    private final static String addPlayerUrl = "http://127.0.0.1:3001/player/add/";
    private final static String removePlayerUrl = "http://127.0.0.1:3001/player/remove/";
    @Autowired
    public void setUserMapper(UserMapper userMapper){
        WebSocketServer.userMapper = userMapper;
    }

    @Autowired
    public  void setRecordMapper(RecordMapper recordMapper) {
        WebSocketServer.recordMapper = recordMapper;
    }

    @Autowired
    public void setBotMapper(BotMapper botMapper){
        WebSocketServer.botMapper = botMapper;
    }

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate){
        WebSocketServer.restTemplate = restTemplate;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        // 建立连接
        this.session = session;
        Integer userId = JwtAuthenticationUtil.getUserId(token);
        this.user = userMapper.selectById(userId);
        if(this.user != null){
            //将该用户存到users集合
            users.put(userId,this);
        }else{
            this.session.close();
        }
    }

    @OnClose
    public void onClose() {
        // 关闭链接
        if(this.user != null){
            users.remove(this.user.getId());
        }
    }

    public static void startGame(Integer aId,Integer aBotId ,Integer bId,Integer bBotId){
        User userA = userMapper.selectById(aId);
        User userB = userMapper.selectById(bId);
        Bot botA = botMapper.selectById(aBotId);
        Bot botB = botMapper.selectById(bBotId);

        Game game = new Game(13,14,20,
                                userA.getId(),botA,
                                userB.getId(),botB);
        game.createMap();
        if(users.get(userA.getId()) != null)
            users.get(userA.getId()).game = game;
        if(users.get(userB.getId()) != null)
            users.get(userB.getId()).game = game;
        game.start();//一局游戏开一个新的线程来维护

        JSONObject respGame = new JSONObject();
        respGame.put("a_id",game.getPlayerA().getId());
        respGame.put("a_sx",game.getPlayerA().getSx());
        respGame.put("a_sy",game.getPlayerA().getSy());
        respGame.put("b_id",game.getPlayerB().getId());
        respGame.put("b_sx",game.getPlayerB().getSx());
        respGame.put("b_sy",game.getPlayerB().getSy());
        respGame.put("gameMap",game.getG());

        JSONObject respA = new JSONObject();
        respA.put("event","start-matching");
        respA.put("opponent_username",userB.getUsername());
        respA.put("opponent_photo",userB.getPhoto());
        respA.put("game",respGame);
//            向A传递相关信息
        if(users.get(userA.getId()) != null)
            users.get(userA.getId()).sendMessage(respA.toJSONString());

        JSONObject respB = new JSONObject();
        respB.put("event","start-matching");
        respB.put("opponent_username",userA.getUsername());
        respB.put("opponent_photo",userA.getPhoto());
        respB.put("game",respGame);
        //向B传递相关信息
        if(users.get(userB.getId()) != null)
            users.get(userB.getId()).sendMessage(respB.toJSONString());

    }

    public void startMatching(Integer botId){
//        向匹配系统MatchingSystem发送请求
        MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
        data.add("user_id",this.user.getId().toString());
        data.add("rating",this.user.getRating().toString());
        data.add("bot_id",botId.toString());
        /*
            String.class是请求完成后返回的结果类型
         */
        restTemplate.postForObject(addPlayerUrl, data, String.class);
    }

    public void stopMatching(){
        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("user_id",this.user.getId().toString());
//        发送post请求
        restTemplate.postForObject(removePlayerUrl,data,String.class);
    }

    public void  move(Integer direction){
        if(game.getPlayerA().getId().equals(user.getId())){
            if(game.getPlayerA().getBotId().equals(-1))
                game.setNextStepA(direction);//只有是玩家操作的时候才去执行
        }else if(game.getPlayerB().getId().equals(user.getId())){
            if(game.getPlayerB().getBotId().equals(-1))
                game.setNextStepB(direction);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 从Client接收消息
        JSONObject data = JSONObject.parseObject(message);
        String event = data.getString("event");
        Integer botId = data.getInteger("bot_id");
        if("start-matching".equals(event)){
            startMatching(botId);
        }else if("stop-matching".equals(event)){
            stopMatching();
        }else if("move".equals(event)){
            move(data.getInteger("direction"));
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void  sendMessage(String message){
//        服务端向客户端发送信息

        //加锁
        synchronized (this.session){
            try {
                //将消息同步发送给建立连接的客户端
                this.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
